import paho.mqtt.client as mqtt
import time
import paho.mqtt.publish as publish
import socket
import serial

HOST = "111.231.134.109"
PORT = 1883

def client_loop():
    try:
    	client_id = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
    	client = mqtt.Client(client_id)
    	client.username_pw_set("MichaelHu", "3735026")
    	client.on_connect = on_connect
    	client.on_message = on_message
    	client.connect(HOST, PORT, 60)
    	ip =  get_host_ip()
    	client.publish("ip", ip, qos=0, retain=False)
    	client.loop_forever()
    except:
    	print("mqtt connect err")

def get_host_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
    except:
	print("no network")
        s.close()
    else:
   	 return ip

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("getip")

def on_message(client, userdata, msg):
     #publish.single("ip", "hello MQTT", qos = 1,hostname=HOST,port=PORT, client_id=client_id,auth = {'username':"admin", 'password':"123456"})
     ip =  get_host_ip()
     client.publish("ip", ip, qos=0, retain=False)
     print(msg.topic+" "+msg.payload.decode("utf-8"))

if __name__ == '__main__':
     client_loop()
